package com.whfc.quality.service.xxl.job;

import com.alibaba.fastjson.JSONObject;
import com.whfc.XxlJobConfig;
import com.whfc.common.util.DateUtil;
import com.whfc.quality.dao.*;
import com.whfc.quality.entity.QualityCheckStatisticsDay;
import com.whfc.quality.entity.QualityTaskItemExec;
import com.whfc.quality.param.QualityCheckParam;
import com.whfc.quality.param.QualityCheckUserParam;
import com.whfc.quality.service.QualityCheckService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 检查任务定时任务
 * @Author hw
 * @Date 2021-08-30 16:25
 * @Version 1.0
 */
@Component
@ConditionalOnBean(XxlJobConfig.class)
public class QualityTaskJob {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private QualityTaskItemExecMapper qualityTaskItemExecMapper;

    @Autowired
    private QualityTaskItemMapper qualityTaskItemMapper;

    @Autowired
    private QualityTaskMapper qualityTaskMapper;

    @Autowired
    private QualityCheckMapper qualityCheckMapper;

    @Autowired
    private QualityCheckStatisticsDayMapper qualityCheckStatisticsDayMapper;

    @Autowired
    private QualityCheckService qualityCheckService;

    @XxlJob("qualityJudgeOverdue")
    public void executeJudgeOverdue() {
        try {
            XxlJobHelper.log("执行昨日已过期的检查任务");
            judgeOverdue();
        } catch (Exception e) {
            XxlJobHelper.handleFail("执行昨日已过期的检查任务失败" + e.getMessage());
        }
    }

    @XxlJob("qualityJudgeState")
    public void executeJudgeState() {
        try {
            XxlJobHelper.log("执行今日开始的任务");
            judgeState();
        } catch (Exception e) {
            XxlJobHelper.handleFail("执行今日开始的任务失败" + e.getMessage());
        }
    }

    @XxlJob("qualityCheckStatisticsDay")
    protected void qualityCheckStatisticsDay() {
        try {
            XxlJobHelper.log("执行质量每天统计的任务");
            //获取时间 统计昨天的质量检查
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            Date yesterday = calendar.getTime();

            List<QualityCheckStatisticsDay> statisticsDayList = new ArrayList<>();

            //取出需要定时统计的组织机构
            List<Integer> list = qualityCheckMapper.selectQualityDeptIds();
            for (Integer deptId : list) {
                QualityCheckStatisticsDay statisticsDay = new QualityCheckStatisticsDay();
                statisticsDay.setDeptId(deptId);
                statisticsDay.setDate(yesterday);
                // 昨天新增
                Integer newIssueNum = qualityCheckMapper.countCheckNewIssue(deptId, DateUtil.getDateBegin(yesterday), DateUtil.getDateEnd(yesterday));
                statisticsDay.setNewIssueNum(newIssueNum);
                // 昨天待整改
                Integer todoIssueNum = qualityCheckMapper.countCheckToBeRectified(deptId);
                statisticsDay.setTodoIssueNum(todoIssueNum);
                // 昨天完成
                Integer completeIssueNum = qualityCheckMapper.countCheckComplete(deptId, yesterday);
                statisticsDay.setCompleteIssueNum(completeIssueNum);
                statisticsDayList.add(statisticsDay);
            }
            //保存记录
            qualityCheckStatisticsDayMapper.batchInsert(statisticsDayList);
        } catch (Exception e) {
            XxlJobHelper.handleFail("执行质量每天统计的任务失败.error:" + e);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    protected void judgeOverdue() {
        List<QualityTaskItemExec> execs = qualityTaskItemExecMapper.selectYesterday();
        if (execs == null || execs.isEmpty()) {
            XxlJobHelper.handleSuccess("没有需要执行的过去任务");
            return;
        }
        XxlJobHelper.log("昨日已过期的检查任务数量：" + execs.size());
        List<Integer> execIds = execs.stream().map(QualityTaskItemExec::getId).distinct().collect(Collectors.toList());
        List<Integer> taskItemIds = execs.stream().map(QualityTaskItemExec::getTaskItemId).distinct().collect(Collectors.toList());
        qualityTaskItemExecMapper.updateOverdue(execIds);
        qualityTaskItemMapper.updateOverdue(taskItemIds);
        XxlJobHelper.handleSuccess();
    }

    @Transactional(rollbackFor = Exception.class)
    protected void judgeState() {
        List<QualityTaskItemExec> execs = qualityTaskItemExecMapper.selectToday();
        if (execs == null || execs.isEmpty()) {
            XxlJobHelper.handleSuccess("今天没有需要开始的任务");
            return;
        }
        XxlJobHelper.log("执行今日开始的任务数量：" + execs.size());
        List<Integer> execIds = execs.stream().map(QualityTaskItemExec::getId).distinct().collect(Collectors.toList());
        List<Integer> taskIds = execs.stream().map(QualityTaskItemExec::getTaskId).distinct().collect(Collectors.toList());
        List<Integer> taskItemIds = execs.stream().map(QualityTaskItemExec::getTaskItemId).distinct().collect(Collectors.toList());
        qualityTaskItemExecMapper.updateStateByExecIds(execIds);
        qualityTaskMapper.updateStateByTaskIds(taskIds);
        qualityTaskItemMapper.updateStateByTaskItem(taskItemIds);
    }


    @XxlJob("qualityGenerateData")
    protected void qualityGenerateData() {
        try {
            XxlJobHelper.log("执行质量演示数据生成");
            String str1 = "{\"deptId\":16,\"partId\":13,\"partName\":\"地基处理/管道低压管道\",\"issueTypeId\":\"738039337744072704\",\"issueTypeName\":\"给排水工程质量\",\"issueId\":\"738041402906116096\",\"issueContent\":\"地漏排水管为镀锌钢管采用焊接\",\"rectifyRequire\":\"结构吊装就位无偏差\",\"rectifyDuration\":\""+cn.hutool.core.date.DateUtil.tomorrow()+"\",\"urgency\":1,\"checkDesc\":\"结构吊装就位偏差过大。\",\"address\":\"陕西省西安市新城区解放门街道宝康宾馆宝康大厦\",\"lng\":108.961622,\"lat\":34.273867,\"imgUrls\":[\"https://files.anculsai.com/ms/pro/quality/img/2022080917595274508.png\"],\"checkUsers\":[{\"type\":2,\"userName\":\"胡俊\",\"userPhone\":\"18672766222\",\"userId\":30},{\"type\":3,\"userName\":\"李华\",\"userPhone\":\"13971675821\",\"userId\":33},{\"type\":4,\"userName\":\"乐洋\",\"userPhone\":\"17363303334\",\"userId\":31},{\"type\":5,\"userName\":\"方戴佳美\",\"userPhone\":\"18971400342\",\"userId\":32}]}";
            String str2 = "{\"deptId\":16,\"partId\":13,\"partName\":\"\\t\\r\\n地基与基础工程/\\t\\r\\n地基开挖支护\\t\\r\\n基坑支护\",\"issueTypeId\":\"737965998958706688\",\"issueTypeName\":\"质量管理\",\"issueId\":\"737988734531665920\",\"issueContent\":\"喷浆不均匀，脱色，掉粉等\",\"rectifyRequire\":\"喷浆均匀，不脱色，不掉粉\",\"rectifyDuration\":\""+cn.hutool.core.date.DateUtil.tomorrow()+"\",\"urgency\":1,\"checkDesc\":\"该工程不合格\",\"address\":\"陕西省西安市新城区解放门街道宝康宾馆宝康大厦\",\"lng\":108.961622,\"lat\":34.273867,\"imgUrls\":[\"https://files.anculsai.com/ms/pro/safety/img/2022080917201643295.png\"],\"checkUsers\":[{\"type\":2,\"userName\":\"王钢\",\"userPhone\":\"17612182237\",\"userId\":35},{\"type\":3,\"userName\":\"潘玉良\",\"userPhone\":\"13886199362\",\"userId\":42},{\"type\":4,\"userName\":\"胡俊\",\"userPhone\":\"18672766222\",\"userId\":30},{\"type\":5,\"userName\":\"李华\",\"userPhone\":\"13971675821\",\"userId\":33}]}";
            String str3 = "{\"deptId\":16,\"partId\":9,\"partName\":\"地基处理/基础验槽钢筋混凝土梁\",\"issueTypeId\":\"738037884002500608\",\"issueTypeName\":\"现场质量\",\"issueId\":\"738038586657472512\",\"issueContent\":\"人防墙体上洞口加强钢筋是否按设计要求预留;\",\"rectifyRequire\":\"人防墙体竖向钢筋锚固长度是否符合设计要求;人防墙体受水平荷载作用\",\"rectifyDuration\":\""+cn.hutool.core.date.DateUtil.tomorrow()+"\",\"urgency\":1,\"checkDesc\":\"墙体竖向钢筋以人防顶底板为支座，施工单位常按平时规范施工，导致墙体竖向钢筋在底板及顶板中的锚固长度不符合设计及规范要求。\",\"address\":\"陕西省西安市新城区解放门街道宝康宾馆宝康大厦\",\"lng\":108.961622,\"lat\":34.273867,\"imgUrls\":[\"https://files.anculsai.com/ms/pro/quality/img/202208091946436852.png\"],\"checkUsers\":[{\"type\":2,\"userName\":\"王钢\",\"userPhone\":\"17612182237\",\"userId\":35},{\"type\":3,\"userName\":\"胡俊\",\"userPhone\":\"18672766222\",\"userId\":30},{\"type\":4,\"userName\":\"胡俊\",\"userPhone\":\"18672766222\",\"userId\":30},{\"type\":5,\"userName\":\"李华\",\"userPhone\":\"13971675821\",\"userId\":33}]}";
            String str4 = "{\"deptId\":16,\"partId\":10,\"partName\":\"地基处理/基础验槽悬臂梁板\",\"issueTypeId\":\"738037884002500608\",\"issueTypeName\":\"现场质量\",\"issueId\":\"738038539156979712\",\"issueContent\":\"人防墙体(外墙、临空墙、防护单元隔墙、密闭墙)钢筋是否均按设计图预留\",\"rectifyRequire\":\"墙体内外侧钢筋规格、间距是否符合设计要求;常见墙体钢筋设计防护区内外侧钢筋规格及间距不同时\",\"rectifyDuration\":\""+cn.hutool.core.date.DateUtil.tomorrow()+"\",\"urgency\":1,\"checkDesc\":\"现场施工防护区内外区分不清，致使内外侧钢筋施工不符设计要求。\",\"address\":\"陕西省西安市新城区解放门街道宝康宾馆宝康大厦\",\"lng\":108.961622,\"lat\":34.273867,\"imgUrls\":[\"https://files.anculsai.com/ms/pro/quality/img/2022080919482249884.png\"],\"checkUsers\":[{\"type\":2,\"userName\":\"潘玉良\",\"userPhone\":\"13886199362\",\"userId\":42},{\"type\":3,\"userName\":\"胡俊\",\"userPhone\":\"18672766222\",\"userId\":30},{\"type\":4,\"userName\":\"胡俊\",\"userPhone\":\"18672766222\",\"userId\":30},{\"type\":5,\"userName\":\"李华\",\"userPhone\":\"13971675821\",\"userId\":33}]}";
            String str5 = "{\"deptId\":16,\"partId\":11,\"partName\":\"地基处理/基础验槽屋面防水工程\",\"issueTypeId\":\"738037884002500608\",\"issueTypeName\":\"现场质量\",\"issueId\":\"738038678705668096\",\"issueContent\":\"后浇带、施工缝不得穿人防口部和临战封堵;\",\"rectifyRequire\":\"底板后浇带、施工缝处及塔吊基础处应有防水处理措施，按《地下工程防水技术规范》GB50108-2008要求执行。\",\"rectifyDuration\":\""+cn.hutool.core.date.DateUtil.tomorrow()+"\",\"urgency\":1,\"checkDesc\":\"不合格\",\"address\":\"陕西省西安市新城区解放门街道宝康宾馆宝康大厦\",\"lng\":108.961622,\"lat\":34.273867,\"imgUrls\":[\"https://files.anculsai.com/ms/pro/quality/img/2022080919494072885.png\"],\"checkUsers\":[{\"type\":2,\"userName\":\"柯祖良\",\"userPhone\":\"15072013434\",\"userId\":38},{\"type\":3,\"userName\":\"胡俊\",\"userPhone\":\"18672766222\",\"userId\":30},{\"type\":4,\"userName\":\"胡俊\",\"userPhone\":\"18672766222\",\"userId\":30},{\"type\":5,\"userName\":\"乐洋\",\"userPhone\":\"17363303334\",\"userId\":31}]}";
            String str6 = "{\"deptId\":16,\"partId\":11,\"partName\":\"地基处理/基础验槽屋面防水工程\",\"issueTypeId\":\"738037884002500608\",\"issueTypeName\":\"现场质量\",\"issueId\":\"738038539156979712\",\"issueContent\":\"人防墙体(外墙、临空墙、防护单元隔墙、密闭墙)钢筋是否均按设计图预留\",\"rectifyRequire\":\"防水达到标准\",\"rectifyDuration\":\""+cn.hutool.core.date.DateUtil.tomorrow()+"\",\"urgency\":1,\"checkDesc\":\"墙体内外侧钢筋规格、间距是否符合设计要求;常见墙体钢筋设计防护区内外侧钢筋规格及间距不同时，现场施工防护区内外区分不清，致使内外侧钢筋施工不符设计要求。\",\"address\":\"陕西省西安市新城区解放门街道宝康宾馆宝康大厦\",\"lng\":108.961622,\"lat\":34.273867,\"imgUrls\":[\"https://files.anculsai.com/ms/pro/quality/img/2022081009544048677.png\"],\"checkUsers\":[{\"type\":2,\"userName\":\"胡俊\",\"userPhone\":\"18672766222\",\"userId\":30},{\"type\":3,\"userName\":\"乐洋\",\"userPhone\":\"17363303334\",\"userId\":31},{\"type\":4,\"userName\":\"左朋\",\"userPhone\":\"13732614623\",\"userId\":36},{\"type\":5,\"userName\":\"潘玉良\",\"userPhone\":\"13886199362\",\"userId\":42}]}";
            String str7 = "{\"deptId\":16,\"partId\":10,\"partName\":\"地基处理/基础验槽悬臂梁板\",\"issueTypeId\":\"738037884002500608\",\"issueTypeName\":\"现场质量\",\"issueId\":\"738038539156979712\",\"issueContent\":\"人防墙体(外墙、临空墙、防护单元隔墙、密闭墙)钢筋是否均按设计图预留\",\"rectifyRequire\":\"墙体内外侧钢筋规格、间距是否符合设计要求;常见墙体钢筋设计防护区内外侧钢筋规格及间距不同时，现场施工防护区内外区分不清，致使内外侧钢筋施工不符设计要求。\",\"rectifyDuration\":\""+cn.hutool.core.date.DateUtil.tomorrow()+"\",\"urgency\":2,\"checkDesc\":\"底板迎水面钢筋混凝土保护层厚度是否≥50mm;检查中常见该质量问题，其主要原因有：底板垫层不平整、底筋垫块间距过大、采用大理石或石块等厚度较小垫块。\",\"address\":\"陕西省西安市新城区解放门街道宝康宾馆宝康大厦\",\"lng\":108.961622,\"lat\":34.273867,\"imgUrls\":[],\"checkUsers\":[{\"type\":2,\"userName\":\"乐洋\",\"userPhone\":\"17363303334\",\"userId\":31},{\"type\":3,\"userName\":\"江阳\",\"userPhone\":\"13521393984\",\"userId\":47},{\"type\":4,\"userName\":\"王钢\",\"userPhone\":\"17612182237\",\"userId\":35},{\"type\":5,\"userName\":\"潘玉良\",\"userPhone\":\"13886199362\",\"userId\":42}]}";

            List<String> strs = Arrays.asList(str1,str2,str3,str4,str5,str6,str7);
            strs.forEach(s -> {
                QualityCheckParam checkParam = JSONObject.parseObject(s,QualityCheckParam.class);
                QualityCheckUserParam userParam = new QualityCheckUserParam();
                userParam.setType(1);
                userParam.setUserId(41);
                userParam.setUserName("冯和任");
                userParam.setUserPhone("13886199362");
                checkParam.getCheckUsers().add(userParam);
                List<QualityCheckUserParam> safetyCheckUserParams = checkParam.getCheckUsers().stream().filter(Objects::nonNull).collect(Collectors.toList());
                Collections.sort(safetyCheckUserParams);
                checkParam.setCheckUsers(safetyCheckUserParams);
                checkParam.setCheckUserId(41);
                checkParam.setCheckUserName("冯和任");
                XxlJobHelper.log(s);
                qualityCheckService.addCheck(checkParam);
            });

        } catch (Exception e) {
            XxlJobHelper.handleFail("执行质量演示数据生成的任务失败.error:" + e);
        }
    }


}
